<?php

namespace Home\Controller;

use Common\Controller\MemberBaseController;
use Common\Model\ErrorLogModel;
use Common\Model\GoodsModel;
use Common\Model\OrderModel;
use Common\Model\SellerModel;
use Vendor\Zhiyoubao\Zhiyoubao\Zhiyoubao;

class ZhiyoubaoController extends MemberBaseController
{

    private $zhiyoubao;

    function __construct()
    {
        parent::__construct();
        $website = "http://plugin.slit.cn/";
        // 智游宝
        vendor("Zhiyoubao.Zhiyoubao");
        $this->zhiyoubao = new Zhiyoubao($website);
    }

    function scenicSpotInfo()
    {
        $id = I('get.id');
        if (!$id)
            $this->error('找不到景区！');
        $model_seller = new SellerModel();
        $info = $model_seller->find($id);
        if (!$info)
            $this->error('找不到景区！');
        $this->assign('info', $info);
        $this->display();
    }

    function getTicketList()
    {
        $seller_id = I('get.seller_id');
        if (!$seller_id)
            $this->error('找不到商品！');
        $where = array('link_seller' => $seller_id, 'status' => 1);
        $model_goods = new GoodsModel();
        $list = $model_goods->where($where)->select();
        $this->assign('list', $list);
        $this->display();
    }

    function getTicket()
    {
        $id = I('get.id');
        if (!$id)
            $this->error('找不到商品！');
        $model_goods = new GoodsModel();
        $info = $model_goods->find($id);
        $this->assign('info', $info);
        $this->display();
    }

    function pay()
    {
        $id = I('get.id');
        $model_goods = new GoodsModel();
        $info_goods = $model_goods->find($id);
        if (!$id) $this->error('商品：' . $id . '找不到票型', true);
        if (!$info_goods['status']) $this->error('用户：' . session('user_id') . '商品：' . $id . '此商品为未上架，不可交易！', true);

        if (IS_POST) {
            // 在本地数据库中添加订单
            $model_order = new OrderModel();
            $data = I('post.');

            $pay_type = 2; // 备用金

            // 如果 该商品 必须填写游玩时间
            if ($info_goods['is_play_date'] and !$data['playDate'])
                $this->error('您必须填写游玩时间！');
            if ($info_goods['is_real'] and (!$data['certificateNo'] or !$data['linkMobile'] or !$data['linkName'])) {
                $this->error('您必须填写实名信息！');
            }

            // 购买数量 超过 库存数量
            if ($data['num'] > $info_goods['stock'])
                $this->error('商品缺货！您最多可购买' . $info_goods['stock'] . ' 个商品');

            // 查询该用户 是否 已经订购过该产品
            $user_id = session('user_id');
            $goods_id = $info_goods['id'];
            $where_order = array(
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'is_pay' => 0
            );
            $is_order = $model_order->where($where_order)->find();
            if (!$is_order) {
                // 客户端支付 - 获取统一订单号 - 并跳转到支付页面
                $req_unionOrderNum = $this->get_unionOrderNum($data['totalPrice'], $info_goods['name'], $info_goods['link_seller'], $data['main_orderCode']);
                $unionOrderNum = $req_unionOrderNum['info'];
                $status_unionOrderNum = $req_unionOrderNum['status'];
                if (!$status_unionOrderNum)
                    $this->error('用户：' . session('user_id') . '订单：' . $is_order['id'] . '统一订单号获取失败！', true);

                // 添加订单
                $add_data = array(
                    'union_order_num' => $unionOrderNum,
                    'goods_id' => $info_goods['id'],
                    'goods_name' => $info_goods['name'],
                    'seller_id' => $info_goods['link_seller'],
                    'addtime' => time(),
                    'playtime' => isset($data['playDate']) ? strtotime($data['playDate']) : time(), // 默认为 当前时间
                    'goods_sn' => $info_goods['sn'],
                    'user_id' => session('user_id'),
                    'real_name' => $data['linkName'],
                    'nick_name' => session('user')['name'],
                    'phone' => session('user')['phone'],
                    'certificate_no' => $data['certificateNo'],
                    'mobile' => $data['linkMobile'],
                    'order_code' => $data['main_orderCode'],
                    'sub_order_code' => $data['sub_orderCode'],
                    'price' => $info_goods['price'],
                    'num' => $data['num'],
                    'total_price' => floatval($info_goods['price']) * floatval($data['num']),  // 手续费
                    'pay_type' => $pay_type,
                    'is_pay' => 0,
                    'is_status' => 0,
                    'is_return' => 0
                );

                if (!$model_order->create($add_data)) {
                    $this->error('用户：' . session('user_id') . ' | 订单：' . $is_order['id'] . ' | 错误：' . $model_order->getError(), true);
                }

                $order_id = $model_order->add($add_data);
                if (!$order_id)
                    $this->error('用户：' . session('user_id') . ' | 订单：' . $is_order['id'] . '添加 订单 失败！', true);
                $this->redirect('/Home/Payment/index/order_id/' . $order_id);
            } else {
                $order_id = $is_order['id'];
                $this->error('您已订过相同产品的订单，正在为您跳转到指定支付页面', false,
                    U('Payment/index', array('order_id' => $order_id)));
            }
            exit();
        }

        $this->assign('info', $info_goods);

        $order_code = $this->zhiyoubao->getOrderCode();
        $sub_order_code = $this->zhiyoubao->getSubOrderCode($order_code);
        $this->assign('order_code', $order_code);
        $this->assign('sub_order_code', $sub_order_code);
        $this->display();
    }


    private function get_unionOrderNum($price, $goods_name, $link_seller, $order_code)
    {
        $req_arr = array();
        // 跳转到支付页面
        // 签名
        $rand_str = random_string(5);
        $sign = md5($order_code . $rand_str);
        $callback_parm = '/order_code/' . $order_code . '/sign/' . $sign;
        $callback = C('PROJECT_URL') . 'index.php/Home/Payment/unionOrderNumCallback' . $callback_parm;
        $amount = $price;
        $des = getFieldByModel('name', 'Seller', $link_seller, '无商铺');
        $remark = '';
        $url = C('MAG_APP_URL') . "core/pay/pay/unifiedOrder?"
            . "trade_no=" . $order_code
            . "&callback=" . $callback
            . "&amount=" . $amount
            . "&title=" . $goods_name
            . "&user_id=" . session('user_id')
            . "&des=" . $des
            . "&remark=" . $remark
            . "&secret=" . C('MAG_SECRET');
        $req = json_decode(file_get_contents($url), true);
        $code = $req['code'];
        $status = $req['success'];
        if (!$status or $code != 100) {
            $req_arr['status'] = 0;
            $req_arr['info'] = "统一订单号获取失败！";
        } else {
            $req_arr['status'] = 1;
            $req_arr['info'] = $req['data']['unionOrderNum'];
        }
        return $req_arr;
    }

//    复写 error
    protected function error($message = '', $is_log = false, $jumpUrl = '', $ajax = false)
    {
        if ($is_log) {
            $model_error_log = new ErrorLogModel();
            $data = array(
                'addtime' => time(),
                'controller' => CONTROLLER_NAME,
                'action' => ACTION_NAME,
                'msg' => $message
            );
            if (!$model_error_log->add($data))
                $this->errFile($message);
        }
        parent::error($message, $jumpUrl, $ajax);
    }

    private function errFile($msg)
    {
        $myfile = fopen("errFile.txt", "w");
        fwrite($myfile, $msg);
        fclose($myfile);
    }

}